<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/30
 * Time: 14:20
 */

namespace App\Api\Controllers;
use App\Models\FriendApply;
use App\Models\FriendModel;
use App\Models\Shareholder;
use App\Services\Behavior;
use App\Services\Log;
use App\Services\Sts;
use App\Services\UserService;
use Illuminate\Http\Request;
use App\Models\Friend;
use App\Models\User;
use App\Models\MemberShip;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class FriendController extends CommonController
{
    protected $friend = null;

    public function __construct()
    {
        parent::__construct();
        $this->getUserInfo();
        $this->friend = new Friend();
    }

    /**
     * 好友列表
     * @return array
     */
    public function friendList()
    {
        $type = IT('type',1);//好友类型
        $page = IT('page',1);
        $limit = IT('limit',15);
        $uid = $this->uid;
        $page = ($page-1) * $limit;
       if($type ==2 ){
         $data = DB::select('SELECT id,name,avatar FROM `users` where id in ( select friend_id from `friend_user` where uid= :uid and status=1) limit :page,:limit ', [':uid'=>$uid,':page'=>$page,':limit'=>$limit]);
       }elseif ($type ==3){
          $data = DB::select('SELECT id,name,avatar FROM `users` where id in ( select uid from `friend_user` where friend_id= :uid and status=1) limit :page,:limit ', [':uid'=>$uid,':page'=>$page,':limit'=>$limit]);
       }

       $duration = strtotime(date('Ymd235959')) - time();
       foreach ($data as &$d) {
           $d->avatar = getSignUrl($d->avatar);
       }
       unset($d);

        return json_success('ok',$data, 10000);
    }

    /**
     * 推荐人列表
     * @return array
     */
    public function recommendList()
    {
        $friend_id = IT('uid');
        $page = IT('page',1);
        $limit = IT('limit',10);
        $uid = $this->uid;
        $friend = $this->friend;
        $page = ($page-1) * $limit;
        $param = [
            'uid' => $uid,
            'limit' => $limit,
            'page' => $page
        ];
        $where  = [
            ['fu.status', '=' , 1],
            ['fu.type', '=', 1],
            ['fu.uid', '=' , $uid]
        ];
        $data = null;
        $data = $friend->getRecommendList($param, $where, $friend_id);

        return json_success('ok',$data, 10000);
    }

    /**
     * 处理好友列表数据
     * @param $data 待处理的好友列表数据
     * @return mixed
     */
    protected function friendHandle($data)
    {
        foreach ($data as $key => $val){
            $data[$key]->vip_level = vip_level_to_name($val->isstockholder,$val->vip_level);
            unset($data[$key]->isstockholder);
        }
        return $data;
    }

    /**
     * 添加关注
     * @return array
     */
    public function friendAdd(Request $request)
    {
        $friend_id = IT('friend_id',true);
        $uid = $this->uid;
        $res_user = D("users")
            ->where(['id' => $friend_id])
            ->first();

        if(empty($res_user))
            EE("该好友的微影号不存在!",0, 10006);
        if((int)$friend_id == (int)$uid)
            EE("不能关注自己!",0, 10007);

        // 检验黑名单
        $is_fail_friend = UserService::check_fail_friend($uid, $friend_id, 1);
        if($is_fail_friend['status'] == '1')
            return json_error($is_fail_friend['message'], [], $is_fail_friend['message_code']);

        $res_friend = D("friend_user")
            ->where([['uid',  $uid], ['friend_id', $friend_id], ['type', 3]])
            ->first();
        $res = true;
        if(!$res_friend){
            $data = [
                'uid' => $uid ,
                'friend_id' =>$friend_id,
                'type'  => 3,
                'status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ];

            DB::beginTransaction();
            $id = DB::table('friend_user')->insertGetId($data);
            $res = $res && $id;

        }else{
            if ($res_friend->status == '1') {
                return json_error('已关注该用户',[], 10008);
            }

            DB::beginTransaction();
            $res = $res && false !== DB::table('friend_user')->where('id', $res_friend->id)->update(['status' => 1]);
        }

        $res = $res && false !== DB::table('users')->where('id', $uid)->increment('attention');  // 用户关注数+1
        $res = $res && false !== DB::table('users')->where('id', $friend_id)->increment('fans'); // 被关注用户粉丝数+1
        if (!$res) {
            DB::rollback();
            return json_error('关注失败，请稍后再试', [], 10009);
        }

        DB::commit();
        return json_success('关注成功', [], 10010);
    }

    /**
     * 取消关注
     * @param Request $request
     * @return array
     */
    public function frienddel(Request $request)
    {
         $friend_id = IT('friend_id',true, '缺少参数', 10011);
         $uid = $this->uid;
         $res_user = D("users")
             ->where(['id' => $friend_id])
             ->first();
         if(empty($res_user)){
             EE("该好友的微影号不存在!", 0, 10012);
         }

         $res_friend = D("friend_user")
             ->where(['uid' => $uid, 'friend_id' => $friend_id, 'status' => 1, 'type' => 3])
             ->first();

         if($res_friend){
             DB::beginTransaction();
             $res = false !== DB::table('friend_user')->where('id', $res_friend->id)->update(['status' => 0]);
             $res = $res && false !== DB::table('users')->where('id', $uid)->decrement('attention');  // 用户关注数-1
             $res = $res && false !== DB::table('users')->where('id', $friend_id)->decrement('fans'); // 被取消关注用户粉丝数-1

             if (!$res) {
                 DB::rollback();
                 return json_error('取消关注失败，请稍后再试', [], 10013);
             }

             DB::commit();
             return json_success('取消关注成功', [], 10014);
         }

         return json_error('未关注过该好友!', [], 10015);

    }

    /**
     * 取消亲友
     * @param Request $request
     * @return array
     */
    public function cancel_friend(Request $request)
    {
        $friend_id = IT('friend_uid',true, '缺少参数',10011);
        $uid = $this->uid;
        $res_user = D("users")->where(['id' => $uid])->first();
        /*if($res_user){
            EE("该亲友的微影号不存在!");
        }*/
        $friend = D("friend")->where([['uid', '=', $uid], ['friend_uid', '=', $friend_id], ['status', '=', '1']])->first();
        if(empty($friend))
            return json_error("亲友不存在", [], 10176);
        if($friend){
            $sql = 'delete from friend where ((uid = ?  and friend_uid= ?) or (friend_uid=? and  uid =?))';
            $upda =  DB::delete($sql, [$uid, $friend_id,$uid, $friend_id]);
        }
        if(!$upda){
            return json_error('操作失败', [], 10001);
        }
        return json_success('取消亲友成功', [], 10177);
    }

    /**
     * 推广会员信息
     */
    public function ExtensionMembers(){
        $user_info = $this->user_info;
        $Members_info= MemberShip::where('mobile','=', $user_info->mobile)->where('status','=',0)->first(['id','name','mobile','number','created_at','certificate', 'member_avatar', 'time_admission']);
        if(empty($Members_info))
            return json_error('会员不存在', [], 10165);

        $member_avatar = '';
        if(!empty($Members_info->member_avatar)){
            $member_avatar_arr = explode('.com/', getSignUrl($Members_info->member_avatar));
            if(count($member_avatar_arr) > 1)
                $member_avatar = env('IMAGE_PROXY_URL').'/'.$member_avatar_arr[1];
        }

        $Members_info->created_at = substr($Members_info->created_at,0,11);
        $Members_info->uid = $this->uid;
        $Members_info->certificate = getSignUrl($Members_info->certificate);
        $Members_info->member_avatar = $member_avatar;
        unset($Members_info->id);
        return json_success('ok', $Members_info, 10000);
    }

    /**
     *推广会员信息保存
     *
     */
    public function MembersPreservation(){
         $mobile = IT('mobile',true,'请填写手机号码', 10016);
         $certificate= IT('certificate',true,'请填写证书地址', 10017);
         $data=MemberShip::where('mobile','=',$mobile)->where('status','=',0)->update(['certificate'=>$certificate]);
         if($data){
           return json_success('ok', [], 10000);
         }else{
           return json_error('保存失败', [], 10001);
         }
    }

    /**
     * 股东信息编辑
     */
    public function shareholderIdentity(Request $request)
    {
        $params = $request->all();

        $mobile = IT('mobile',true,'请填写手机号码', 10018);
        $name = IT('name',true,'请填写姓名', 10019);
        $id_card = IT('id_card',true,'请填写身份证号码', 10020);
        $positive_card = IT('positive_card',true,'身份证正面不能为空', 10021);
        $opposite_card = IT('opposite_card',true,'身份证反面不能为空', 10022);
        $Birthday = IT('Birthday',true,'请填写生日日期', 10023);
        $address = IT('address',true,'请填写地址', 10024);
        $bank_number = IT('bank_number',true,'请填写银行卡号', 10025);
        $bank_name = IT('bank_name',true,'请填写银行名称', 10026);
        $opening_bank = IT('opening_bank',true,'请填写开户行名称', 10027);
        $bank_address = IT('bank_address',true,'请填写开户行城市', 10028);

        $params['Birthday'] = date('Y/m/d', strtotime($Birthday));

        // 判断会员和股东是否匹配  认证字段未使用
        if($this->user_info->mobile != $mobile)
            return json_error('股东手机号不匹配', [] , 10029);

        // 完善资料，待签名
        $params['operation_status'] = 1;
        // 新增/编辑
        $result = Shareholder::updateData($params);
        if(isset($result['status']) && $result['status'] == 'success')
            return json_success('ok',$result['data']);

        $message = isset($result['message']) ? $result['message'] : '操作异常';
        $message_code = isset($result['message_code']) ? $result['message_code'] : '10001';
        return json_error($message, [], $message_code);
    }

    /**
     * 股东信息
     */
    public function ShareholderInfo(Request $request){

        $feild = ['mobile', 'user_name', 'total_funds', 'status','certificate_number', 'arrival_account',  'operation_status', 'share', 'id_card', 'Birthday', 'address', 'bank_name','bank_address', 'opening_bank',
                'bank_number', 'created_at', 'updated_at', 'sign_img', 'shareholder_agree_img', 'shareholder_certificate_img', 'positive_card', 'opposite_card', 'inherit_name', 'inherit_card', 'inherit_mobile', 'inherit_sex'
        ];
        $shareholder= Shareholder::where('mobile','=',$this->user_info->mobile)->orderBy('id','desc')->first($feild);
        if(empty($shareholder) || $shareholder->status == 1)
            return json_error('无此用户', [], 10030);

        $shareholder->sign_img = getSignUrl($shareholder->sign_img);
        // 协议
        if(!empty($shareholder->shareholder_agree_img)){
            $shareholder_agree_img_arr = explode(',', $shareholder->shareholder_agree_img);
            sort($shareholder_agree_img_arr);
            $temp_arr = [];
            foreach ($shareholder_agree_img_arr as $value)
                $temp_arr[] = getSignUrl($value);
            $shareholder->shareholder_agree_img = empty($temp_arr) ? null : $temp_arr;
        }

        // 股东证书
        if(!empty($shareholder->shareholder_certificate_img)){
            $shareholder_certificate_img_arr = explode(',', $shareholder->shareholder_certificate_img);
            sort($shareholder_certificate_img_arr);
            $temp_arr = [];
            foreach ($shareholder_certificate_img_arr as $value)
                $temp_arr[] = getSignUrl($value);
            $shareholder->shareholder_certificate_img = empty($temp_arr) ? null : $temp_arr;
        }

        $positive_card = '';
        if(!empty($shareholder->positive_card)){
            $positive_card_arr = explode('.com/', getSignUrl($shareholder->positive_card));
            if(count($positive_card_arr) > 1)
                $positive_card = env('IMAGE_PROXY_URL').'/'.$positive_card_arr[1];
        }
        $opposite_card = '';
        if(!empty($shareholder->positive_card)){
            $opposite_card_arr = explode('.com/', getSignUrl($shareholder->opposite_card));
            if(count($positive_card_arr) > 1)
                $opposite_card = env('IMAGE_PROXY_URL').'/'.$opposite_card_arr[1];
        }

        $shareholder->inherit_name = empty($shareholder->inherit_name) ? null : $shareholder->inherit_name;
        $shareholder->inherit_card = empty($shareholder->inherit_card) ? null : $shareholder->inherit_card;
        $shareholder->inherit_mobile = empty($shareholder->inherit_mobile) ? null : $shareholder->inherit_mobile;
        $shareholder->arrival_account = empty($shareholder->arrival_account) ? 0 : strtotime($shareholder->arrival_account);
        $shareholder->positive_card = $positive_card;
        $shareholder->opposite_card = $opposite_card;
        $TotalStock = config('admin.TotalStock');//总注册资金
        $shareholder->ratio  =  ($shareholder->share > 0 ) ? $shareholder->share*100/$TotalStock : 0;
        $shareholder->birthday = $shareholder->Birthday;
        $shareholder->sign_img = getSignUrl($shareholder->sign_img);
        $shareholder->status = $shareholder->operation_status;
        $shareholder->updated_at  =  (!empty($shareholder->updated_at)) ? strtotime($shareholder->updated_at) : strtotime($shareholder->created_at);
        unset($shareholder->created_at,$shareholder->Birthday);

        return json_success('ok', $shareholder, 10000);
    }

}
